package scau.gsmg.misp.dao.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import scau.gsmg.misp.dao.BaseDAO;
import scau.gsmg.misp.dao.IReturnGoodsDAO;
import scau.gsmg.misp.vo.Payment;
import scau.gsmg.misp.vo.SaleOrder;
import scau.gsmg.misp.vo.SaleOrderItems;
import scau.gsmg.misp.vo.SaleReturn;
import scau.gsmg.misp.vo.SaleReturnItems;
import scau.gsmg.misp.vo.User;

/**
 * @Title 退货
 * @Group gaoshenmegui
 * @author ZCL
 * @date 2015年5月9日
 */
@Repository
public class ReturnGoodsDAO extends BaseDAO implements IReturnGoodsDAO {
	
	private static final Logger logger = Logger.getLogger(ReturnGoodsDAO.class);
	
	/**
	 * 通过支付单号得到销售单号
	 */
	@Override
	public String gainSaleOrderId(String paymentId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		try {
			String hql = "from Payment p where p.paymentId=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, paymentId);
			List<Payment> payment = query.list();
			if(payment.size()>0){
				return payment.get(0).getSaleOrder().getSaleOrderId();
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}
	
	/**
	 * 通过支付单号得到销售单号
	 */
	@Override
	public int gainSaleId(String paymentId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		try {
			String hql = "from Payment p where p.paymentId=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, paymentId);
			List<Payment> payment = query.list();
			if(payment.size()>0){
				return payment.get(0).getSaleOrder().getId();
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return 0;
	}
	
	/**
	 * 获取单据中的商品
	 */
	@Override
	public List gainGoods(String saleOrderId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		String hql = "from SaleOrderItems s where s.saleOrder.saleOrderId=?";
		List dataList = new ArrayList();
		try {
			Query query = session.createQuery(hql);
			query.setParameter(0, saleOrderId);
			List<SaleOrderItems> goods = query.list();
			for (SaleOrderItems s : goods) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", s.getGoods().getId());
				jsonMap.put("barcode", s.getGoods().getBarcode());
				jsonMap.put("name", s.getGoods().getName());
				jsonMap.put("price", s.getGoods().getPrice());
				jsonMap.put("unit", s.getGoods().getUnit());
				jsonMap.put("amount", s.getQuantity());
				jsonMap.put("totalprice", s.getPrice());
				dataList.add(jsonMap);
			}
			return dataList;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 得到销售单信息
	 */
	@Override
	public List gainSaleOrder(String paymentId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		String hql = "from Payment p where p.paymentId=?";
		List dataList = new ArrayList();
		try {
			Query query = session.createQuery(hql);
			query.setParameter(0, paymentId);
			List<Payment> payment = query.list();
			for (Payment p : payment) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				if(p.getSaleOrder().getMember()!=null){
					jsonMap.put("customerId", p.getSaleOrder().getMember().getId());
					jsonMap.put("discount", p.getSaleOrder().getMember().getDiscount());
				}else{
					jsonMap.put("customerId","非会员");
					jsonMap.put("discount","1");
				}
				dataList.add(jsonMap);
			}
			return dataList;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}
	/**
	 * 获取退货表最新一条记录
	 */
	@Override
	public String lastReturnRecord() throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		// 查询最后一条记录
		String hql = "from SaleReturn r where r.saleReturnId=(select max(r.saleReturnId) from SaleReturn r)";
		try {
			Query query = session.createQuery(hql);
			List<SaleReturn> item = query.list();
			String strOrder = null;
			if (item.size() > 0) {
				SaleReturn order = (SaleReturn) item.get(0);
				strOrder = order.getSaleReturnId();
			}
			if (strOrder == null) {
				return null;
			} else {
				return strOrder;
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}
	/**
	 * 生成退货记录
	 */
	@Override
	public SaleReturn createSaleReturn(String returnId,SaleOrder saleOrder,double total,int amount,User user,Timestamp time) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		try {
			SaleReturn saleReturn = new SaleReturn();
			saleReturn.setAmount(amount);
			saleReturn.setCreateTime(time);
			saleReturn.setSaleOrder(saleOrder);
			saleReturn.setSaleReturnId(returnId);
			saleReturn.setTotal(total);
			saleReturn.setUser(user);
			Transaction tx = session.beginTransaction();
			session.save(saleReturn);
			tx.commit();
			return saleReturn;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}
	/**
	 * 在退货商品表生成记录
	 */
	@Override
	public boolean writeReturnGoods(String rowObj, SaleReturn saleReturn,String saleOrderId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		boolean flag = false;
		try {
			JSONArray jsonArray = JSONArray.fromObject(rowObj);// 把从前台得到的json字符串转换成json数组
			// 将每一条商品记录保存到数据库
			for (int i = 0; i < jsonArray.size(); i++) {
				String hql = "from SaleOrderItems s where s.saleOrder.saleOrderId=?";
				Query query = session.createQuery(hql);
				query.setParameter(0, saleOrderId);
				List list = query.list();
				SaleOrderItems saleOrderItems = (SaleOrderItems) list.get(0);

				int quantity = jsonArray.getJSONObject(i).getInt("amount");// 得到数量
				double price = jsonArray.getJSONObject(i).getDouble("totalprice");// 得到价格
				String reason = jsonArray.getJSONObject(i).getString("reason");// 得到价格
				
				SaleReturnItems saleReturnItems = new SaleReturnItems();
				saleReturnItems.setPrice(price);
				saleReturnItems.setQuantity(quantity);
				saleReturnItems.setSaleReturn(saleReturn);
				saleReturnItems.setSaleOrderItems(saleOrderItems);
				saleReturnItems.setReason(reason);
				Transaction tx = session.beginTransaction();

				session.save(saleReturnItems);
				tx.commit();
			}
			flag = true;

		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 得到销售单对象
	 */
	@Override
	public SaleOrder gainSaleOrderObj(String saleOrderId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		try {
			String hql = "from SaleOrder s where s.saleOrderId=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, saleOrderId);
			List<SaleOrder> list = query.list();
			SaleOrder saleOrder = new SaleOrder();
			if (list.size() > 0) {
				saleOrder = (SaleOrder) list.get(0);
			}else{
				saleOrder = null;
			}
			return saleOrder;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}
	/**
	 * 通过用户ID返回用户对象
	 */
	@Override
	public User gainUser(int userId) throws Exception {
		Session session = getSession();
		try {
			String hql = "from User u where u.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, userId);
			List list = query.list();
			User user = new User();
			if (list.size() > 0) {
				user = (User) list.get(0);
			} else {
				user = null;
			}
			return user;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 退货后，更新销售商品表
	 */
	@Override
	public boolean updateSaleOrderItems(String rowObj,int saleOrderId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		boolean flag = false;
		try {
			JSONArray jsonArray = JSONArray.fromObject(rowObj);// 把从前台得到的json字符串转换成json数组
			// 将每一条商品记录保存到数据库
			for (int i = 0; i < jsonArray.size(); i++) {
				String hql = "update SaleOrderItems s set s.quantity=s.quantity-?,s.price=s.price-? where s.saleOrder.id=? and s.goods.id=?";
				Query query = session.createQuery(hql);
				int quantity = jsonArray.getJSONObject(i).getInt("amount");// 得到数量
				double totalprice = jsonArray.getJSONObject(i).getDouble("totalprice");// 得到金额
				int goodId = jsonArray.getJSONObject(i).getInt("id");
				query.setParameter(0, quantity);
				query.setParameter(1, totalprice);
				query.setParameter(2, saleOrderId);
				query.setParameter(3, goodId);
				query.executeUpdate();
			}
			flag = true;

		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 修改原支付单信息（更新找款）
	 */
	@Override
	public boolean updatePayment(double totalReturn,int saleOrderId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		boolean flag = false;
		try {
			String hql = "update Payment p set p.changes=p.changes+? where p.saleOrder.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, totalReturn);
			query.setParameter(1, saleOrderId);
			query.executeUpdate();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 修改原销售单信息（更新总数量，总金额，应收款）
	 */
	@Override
	public boolean updateSaleOrder(int amount, double totalPrice,
			double totalReturn,int saleId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		boolean flag = false;
		try {
			String hql = "update SaleOrder s set s.amount=s.amount-?,s.totalPrice=s.totalPrice-?,s.receivable=s.receivable-? where s.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, amount);
			query.setParameter(1, totalPrice);
			query.setParameter(2, totalReturn);
			query.setParameter(3, saleId);
			query.executeUpdate();
			flag=true;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 更新会员积分
	 */
	@Override
	public boolean updateIntegral(int customerId, int integral)
			throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		try {
			// 0代表该用户不是会员
			if (customerId != 0) {
				String hql = "update Member m set m.integral=m.integral-? where m.id=?";
				Query query = session.createQuery(hql);
				query.setParameter(0, integral);
				query.setParameter(1, customerId);
				query.executeUpdate();
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		
		return false;
	}
	
	
}
